
import com.ridgesoft.intellibrain.IntelliBrain;
import com.ridgesoft.io.Display;
import javax.comm.SerialPort;

public class MasterBoard_NoSlave extends Thread {

    private Mailbox hostMail = null;
    private Display display = IntelliBrain.getLcdDisplay();
    private ReceiveThread hostRecThread;
    protected static char heading = 'N';
    protected static int robotX = 0;
    protected static int robotY = 0;

    public static void main(String[] args) {
        MasterBoard_NoSlave mb = new MasterBoard_NoSlave();
        mb.start();
    }

    public void run() {
        // Connect to host
        connectToHost();

        while (hostMail == null) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException ex) {
            }
        }
        // Start receiving messages thread
        hostRecThread = new ReceiveThread(hostMail);
        hostRecThread.start();

        display.print(0, "RecThread Started");
        // Create variable for host messages
        byte[] hostMessage = null;
        /*try {
            hostMail.postMessage(new byte[]{0});
        } catch (IOException ex) {
        }*/
        // Start main while loop
        while (true) {
            display.print(1, "Waiting");
            if (hostRecThread.hasMessage()) {
                //Handle message from host
                display.print(0, "Rec'd message");
                hostMessage = hostRecThread.getMessage();
                try {
                    ProcessHostMessage phm = new ProcessHostMessage(hostMessage, display, hostMail, null, heading, robotX, robotY);
                    phm.run();
                } catch (Exception ex) {
                    // Thread already running.
                    display.print(1, "Wait");
                }

            }
        }
    }

    private void connectToHost() {
        try {
            display.print(0, "Connecting...");
            SerialPort port = IntelliBrain.getCom1();
            port.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            hostMail = new Mailbox(port.getInputStream(), port.getOutputStream(), 50, 1);
            hostMail.open();
            display.print(0, "Connected");
        } catch (Exception ex) {
            display.print(0, "Com Error");
        }
    }
}
